﻿using System;
using System.Linq;
using System.Web.Mvc;
using BLL;
using Model;

namespace Web.Areas.Manager.Controllers
{
    [NoCache]
    [HandleError]
    [UserAuthorize]
    public partial class Sys_UsersController : Controller
    {
        Sys_Users_BLL _Sys_Users_BLL = new Sys_Users_BLL();
        Sys_Roles_BLL _Sys_Roles_BLL = new Sys_Roles_BLL();
        Sys_UsersInRoles_BLL _Sys_UsersInRoles_BLL = new Sys_UsersInRoles_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _Sys_Users_BLL.Get();
            if (!string.IsNullOrEmpty(keyword))
            {
                model = model.Where(a => a.UserName.Contains(keyword));
            }
            return View(model.ToPagedList(pageIndex));
        }

        public virtual ActionResult Edit(Guid? id)
        {
            var item = _Sys_Users_BLL.Get(id);

            ViewData.Add("Sys_Roles", _Sys_Roles_BLL.Get());

            return View(item);
        }

        [HttpPost]
        public virtual ActionResult Edit(Guid? id, Sys_Users collection)
        {
            Edit(id);

            if (!ModelState.IsValid)
            {
                return View();
            }

            _Sys_Users_BLL.Save(id, ref collection);

            //保存用户所属角色

            foreach (var item in _Sys_Roles_BLL.Get())
            {
                _Sys_UsersInRoles_BLL.Delete(collection.Id, item.Id);

                if (Request[item.Id.ToString()] != "false")
                {
                    _Sys_UsersInRoles_BLL.Insert(collection.Id, item.Id);
                }
            }

            return RedirectToAction("Index");
        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            _Sys_Users_BLL.DeleteObject(Id);
            return RedirectToAction("Index");
        }
    }
}
